<template>
  <div class="file-list-container">
    <div class="header">
      <h2>文件管理</h2>
      <div class="header-actions">
        <el-button @click="$router.push('/upload')" type="primary">上传文件</el-button>
        <el-button @click="$router.push('/')" plain>返回首页</el-button>
      </div>
    </div>
    
    <div class="content">
      <el-card shadow="hover" v-loading="loading">
        <template #header>
          <div class="card-header">
            <span>文件列表</span>
            <el-button @click="fetchFileList" :loading="refreshing" circle>
              <el-icon><Refresh /></el-icon>
            </el-button>
          </div>
        </template>
        
        <div class="table-container">
          <el-table 
            :data="fileList" 
            style="width: 100%" 
            stripe
            class="file-table"
            :header-cell-style="{
              background: 'var(--background-color)',
              color: 'var(--text-color)',
              fontWeight: '600'
            }"
          >
            <el-table-column label="文件名称" min-width="180">
              <template #default="scope">
                <div class="file-name-cell">
                  <el-icon><Document /></el-icon>
                  <el-link type="primary" @click="previewFile(scope.row)">
                    {{ scope.row.originalFileName }}
                  </el-link>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column label="文件大小" width="120">
              <template #default="scope">
                {{ formatFileSize(scope.row.fileSize) }}
              </template>
            </el-table-column>
            
            <el-table-column label="下载码" width="100">
              <template #default="scope">
                <el-tag type="success" effect="plain">{{ scope.row.downloadCode }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column label="下载次数" width="100" align="center">
              <template #default="scope">
                {{ scope.row.downloadCount }}
              </template>
            </el-table-column>
            
            <el-table-column label="上传时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.uploadTime) }}
              </template>
            </el-table-column>
            
            <el-table-column label="过期时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.expirationTime) }}
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <div class="action-buttons">
                  <el-button
                    type="primary"
                    link
                    @click="handleDownload(scope.row)"
                  >
                    下载
                  </el-button>
                  <el-button
                    type="danger"
                    link
                    @click="handleDelete(scope.row)"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div class="empty-block" v-if="fileList.length === 0 && !loading">
          <el-empty description="暂无文件记录">
            <el-button type="primary" @click="$router.push('/upload')">上传文件</el-button>
          </el-empty>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Document } from '@element-plus/icons-vue'
import { formatFileSize, formatDateTime } from '../utils/format'
import api from '../utils/api'

export default {
  name: 'FileListPage',
  components: {
    Refresh,
    Document
  },
  setup() {
    const router = useRouter()
    const loading = ref(true)
    const refreshing = ref(false)
    const fileList = ref([])
    
    onMounted(() => {
      fetchFileList()
    })
    
    const fetchFileList = async () => {
      if (refreshing.value) return
      
      refreshing.value = true
      loading.value = true
      
      try {
        const response = await api.getFileList()
        const { code, data, message } = response.data
        
        if (code === 200) {
          fileList.value = data || []
        } else {
          ElMessage.error(message || '获取文件列表失败')
        }
      } catch (error) {
        console.error('获取文件列表错误', error)
        ElMessage.error('获取文件列表失败，请稍后重试')
      } finally {
        loading.value = false
        refreshing.value = false
      }
    }
    
    const previewFile = (file) => {
      router.push(`/file/${file.downloadCode}`)
    }
    
    const handleDownload = (file) => {
      // 创建下载链接
      const downloadUrl = `/api/files/download/${file.downloadCode}`
      
      // 创建隐藏的a标签实现下载
      const link = document.createElement('a')
      link.href = downloadUrl
      link.download = file.originalFileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      ElMessage.success('文件下载已开始')
    }
    
    const handleDelete = (file) => {
      ElMessageBox.confirm(
        `确定要删除文件 "${file.originalFileName}" 吗？删除后将无法恢复！`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await api.deleteFile(file.fileKey)
          const { code, message } = response.data
          
          if (code === 200) {
            ElMessage.success('文件删除成功')
            // 刷新文件列表
            fetchFileList()
          } else {
            ElMessage.error(message || '删除文件失败')
          }
        } catch (error) {
          console.error('删除文件错误', error)
          ElMessage.error('删除文件失败，请稍后重试')
        }
      }).catch(() => {
        // 用户取消删除
      })
    }
    
    return {
      loading,
      refreshing,
      fileList,
      formatFileSize,
      formatDateTime,
      fetchFileList,
      previewFile,
      handleDownload,
      handleDelete
    }
  }
}
</script>

<style scoped>
.file-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  font-size: 1.8rem;
  font-weight: 700;
  color: var(--primary-color);
  margin: 0;
  letter-spacing: -0.5px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.content {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 1.2rem;
  font-weight: 600;
  color: var(--text-color);
}

.table-container {
  overflow-x: auto;
  margin: 0 -1px;
}

.file-table {
  border-radius: 8px;
  overflow: hidden;
}

.file-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-name-cell i {
  color: var(--primary-color);
}

.empty-block {
  margin: 30px 0;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.action-buttons {
  display: flex;
  justify-content: space-around;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .file-list-container {
    padding: 15px;
  }
  
  .header h2 {
    font-size: 1.5rem;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: center;
    gap: 8px;
  }
}

@media (max-width: 480px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
  }
  
  .header-actions .el-button {
    flex: 1;
  }
}
</style> 